/*
 * Copyright (C) 2013 Noralf Tronnes
 *
 * This driver is inspired by:
 *   st7735fb.c, Copyright (C) 2011, Matt Porter
 *   broadsheetfb.c, Copyright (C) 2008, Jaya Kumar
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/fb.h>
#include <linux/gpio.h>
#include <linux/spi/spi.h>
#include <linux/delay.h>
#include <linux/uaccess.h>
#include <linux/backlight.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#include <linux/dma-mapping.h>
#include <linux/of.h>
#include <linux/of_gpio.h>

#include "fbtft.h"
#include "ili9488cmds.h"
#include "ili9488_regs.h"

int fbtft_verify_gpios(struct device *dev,struct fbtft_par *par);

//int set_var(struct fbtft_par *par);

extern void fbtft_sysfs_init(struct fbtft_par *par);
extern void fbtft_sysfs_exit(struct fbtft_par *par);
extern void fbtft_expand_debug_value(unsigned long *debug);
extern int fbtft_gamma_parse_str(struct device *dev,struct fbtft_par *par, unsigned long *curves,
						const char *str, int size);

static unsigned long debug;
module_param(debug, ulong , 0);
MODULE_PARM_DESC(debug, "override device debug level");

static bool dma = false;
module_param(dma, bool, 0);
MODULE_PARM_DESC(dma, "Use DMA buffer");


void fbtft_dbg_hex(const struct device *dev, int groupsize,
			void *buf, size_t len, const char *fmt, ...)
{
	va_list args;
	static char textbuf[512];
	char *text = textbuf;
	size_t text_len;

	va_start(args, fmt);
	text_len = vscnprintf(text, sizeof(textbuf), fmt, args);
	va_end(args);

	hex_dump_to_buffer(buf, len, 32, groupsize, text + text_len,
				512 - text_len, false);

	if (len > 32)
		dev_info(dev, "%s ...\n", text);
	else
		dev_info(dev, "%s\n", text);
}
EXPORT_SYMBOL(fbtft_dbg_hex);

unsigned long fbtft_request_gpios_match(struct fbtft_par *par,
					const struct fbtft_gpio *gpio)
{
	int ret;
	long val;

	fbtft_par_dbg(DEBUG_REQUEST_GPIOS_MATCH, par, "%s('%s')\n",
		__func__, gpio->name);

	if (strcasecmp(gpio->name, "reset") == 0) {
		par->gpio.reset = gpio->gpio;
		return GPIOF_OUT_INIT_HIGH;
	} else if (strcasecmp(gpio->name, "dc") == 0) {
		par->gpio.dc = gpio->gpio;
		return GPIOF_OUT_INIT_LOW;
	} else if (strcasecmp(gpio->name, "cs") == 0) {
//		par->gpio.cs = gpio->gpio;
		return GPIOF_OUT_INIT_HIGH;
	} else if (strcasecmp(gpio->name, "wr") == 0) {
//		par->gpio.wr = gpio->gpio;
		return GPIOF_OUT_INIT_HIGH;
	} else if (strcasecmp(gpio->name, "rd") == 0) {
//		par->gpio.rd = gpio->gpio;
		return GPIOF_OUT_INIT_HIGH;
	} else if (strcasecmp(gpio->name, "latch") == 0) {
//		par->gpio.latch = gpio->gpio;
		return GPIOF_OUT_INIT_LOW;
	} else if (gpio->name[0] == 'd' && gpio->name[1] == 'b') {
		ret = kstrtol(&gpio->name[2], 10, &val);
		if (ret == 0 && val < 16) {
			par->gpio.db[val] = gpio->gpio;
			return GPIOF_OUT_INIT_LOW;
		}
	} else if (strcasecmp(gpio->name, "led") == 0) {
		par->gpio.led[0] = gpio->gpio;
		return GPIOF_OUT_INIT_LOW;
	} else if (strcasecmp(gpio->name, "led_") == 0) {
		par->gpio.led[0] = gpio->gpio;
		return GPIOF_OUT_INIT_HIGH;
	}

	return FBTFT_GPIO_NO_MATCH;
}

int fbtft_request_gpios(struct device *dev,struct fbtft_par *par)
{
	struct fbtft_platform_data *pdata = par->pdata;
	const struct fbtft_gpio *gpio;
	unsigned long flags;
	int ret;

	if (pdata && pdata->gpios) {
		gpio = pdata->gpios;
		while (gpio->name[0]) {
			flags = FBTFT_GPIO_NO_MATCH;
			/* if driver provides match function, try it first,
			   if no match use our own */
//			if (par->fbtftops.request_gpios_match)
//				flags = par->fbtftops.request_gpios_match(par, gpio);
			if (flags == FBTFT_GPIO_NO_MATCH)
				flags = fbtft_request_gpios_match(par, gpio);
			if (flags != FBTFT_GPIO_NO_MATCH) {
				ret = devm_gpio_request_one(dev,
						gpio->gpio, flags,
						dev->driver->name);
				if (ret < 0) {
					dev_err(dev,
						"%s: gpio_request_one('%s'=%d) failed with %d\n",
						__func__, gpio->name,
						gpio->gpio, ret);
					return ret;
				}
//				fbtft_par_dbg(DEBUG_REQUEST_GPIOS, par,
//					"%s: '%s' = GPIO%d\n",
//					__func__, gpio->name, gpio->gpio);
			}
			gpio++;
		}
	}

	return 0;
}


static int fbtft_request_one_gpio(struct device *dev,struct fbtft_par *par,
				  const char *name, int index, int *gpiop)
{
	struct device_node *node = dev->of_node;
	int gpio, flags, ret = 0;
	enum of_gpio_flags of_flags;

	if (of_find_property(node, name, NULL)) {
		gpio = of_get_named_gpio_flags(node, name, index, &of_flags);
		if (gpio == -ENOENT)
			return 0;
		if (gpio == -EPROBE_DEFER)
			return gpio;
		if (gpio < 0) {
			dev_err(dev,
				"failed to get '%s' from DT\n", name);
			return gpio;
		}

		/* active low translates to initially low */
		flags = (of_flags & OF_GPIO_ACTIVE_LOW) ? GPIOF_OUT_INIT_LOW :
							GPIOF_OUT_INIT_HIGH;
		ret = devm_gpio_request_one(dev, gpio, flags,
						dev->driver->name);
		if (ret) {
			dev_err(dev,
				"gpio_request_one('%s'=%d) failed with %d\n",
				name, gpio, ret);
			return ret;
		}
		if (gpiop)
			*gpiop = gpio;
//		fbtft_par_dbg(DEBUG_REQUEST_GPIOS, par, "%s: '%s' = GPIO%d\n",
//							__func__, name, gpio);
	}

	return ret;
}

static int fbtft_request_gpios_dt(struct device *dev,struct fbtft_par *par)
{
//	int i;
	int ret;

	if (!par->info->device->of_node)
		return -EINVAL;

	ret = fbtft_request_one_gpio(dev,par, "reset-gpios", 0, &par->gpio.reset);
	if (ret)
		return ret;
	ret = fbtft_request_one_gpio(dev,par, "dc-gpios", 0, &par->gpio.dc);
	if (ret)
		return ret;
//	ret = fbtft_request_one_gpio(par, "rd-gpios", 0, &par->gpio.rd);
//	if (ret)
//		return ret;
//	ret = fbtft_request_one_gpio(par, "wr-gpios", 0, &par->gpio.wr);
//	if (ret)
//		return ret;
//	ret = fbtft_request_one_gpio(par, "cs-gpios", 0, &par->gpio.cs);
//	if (ret)
//		return ret;
//	ret = fbtft_request_one_gpio(par, "latch-gpios", 0, &par->gpio.latch);
//	if (ret)
//		return ret;
//	for (i = 0; i < 16; i++) {
//		ret = fbtft_request_one_gpio(par, "db-gpios", i,
//						&par->gpio.db[i]);
//		if (ret)
//			return ret;
//		ret = fbtft_request_one_gpio(par, "led-gpios", i,
//						&par->gpio.led[i]);
//		if (ret)
//			return ret;
//		ret = fbtft_request_one_gpio(par, "aux-gpios", i,
//						&par->gpio.aux[i]);
//		if (ret)
//			return ret;
//	}

	return 0;
}


#ifdef CONFIG_FB_BACKLIGHT
int fbtft_backlight_update_status(struct backlight_device *bd)
{
	struct fbtft_par *par = bl_get_data(bd);
	bool polarity = !!(bd->props.state & BL_CORE_DRIVER1);

//	fbtft_par_dbg(DEBUG_BACKLIGHT, par,
//		"%s: polarity=%d, power=%d, fb_blank=%d\n",
//		__func__, polarity, bd->props.power, bd->props.fb_blank);

	if ((bd->props.power == FB_BLANK_UNBLANK) && (bd->props.fb_blank == FB_BLANK_UNBLANK))
		gpio_set_value(par->gpio.led[0], polarity);
	else
		gpio_set_value(par->gpio.led[0], !polarity);

	return 0;
}

int fbtft_backlight_get_brightness(struct backlight_device *bd)
{
	return bd->props.brightness;
}

void fbtft_unregister_backlight(struct device *dev,struct fbtft_par *par)
{
	const struct backlight_ops *bl_ops;

//	fbtft_par_dbg(DEBUG_BACKLIGHT, par, "%s()\n", __func__);

	if (par->info->bl_dev) {
		par->info->bl_dev->props.power = FB_BLANK_POWERDOWN;
		backlight_update_status(par->info->bl_dev);
		bl_ops = par->info->bl_dev->ops;
		backlight_device_unregister(par->info->bl_dev);
		par->info->bl_dev = NULL;
	}
}

void fbtft_register_backlight(struct device *dev,struct fbtft_par *par)
{
	struct backlight_device *bd;
	struct backlight_properties bl_props = { 0, };
	struct backlight_ops *bl_ops;

//	fbtft_par_dbg(DEBUG_BACKLIGHT, par, "%s()\n", __func__);

	if (par->gpio.led[0] == -1) {
//		fbtft_par_dbg(DEBUG_BACKLIGHT, par,
//			"%s(): led pin not set, exiting.\n", __func__);
		return;
	}

	bl_ops = devm_kzalloc(par->info->device, sizeof(struct backlight_ops),
				GFP_KERNEL);
	if (!bl_ops) {
		dev_err(par->info->device,
			"%s: could not allocate memeory for backlight operations.\n",
			__func__);
		return;
	}

	bl_ops->get_brightness = fbtft_backlight_get_brightness;
	bl_ops->update_status = fbtft_backlight_update_status;
	bl_props.type = BACKLIGHT_RAW;
	/* Assume backlight is off, get polarity from current state of pin */
	bl_props.power = FB_BLANK_POWERDOWN;
	if (!gpio_get_value(par->gpio.led[0]))
		bl_props.state |= BL_CORE_DRIVER1;

	bd = backlight_device_register(dev_driver_string(par->info->device),
				dev, par, bl_ops, &bl_props);
	if (IS_ERR(bd)) {
		dev_err(dev,
			"cannot register backlight device (%ld)\n",
			PTR_ERR(bd));
		return;
	}
	par->info->bl_dev = bd;

	if (!par->fbtftops.unregister_backlight)
		par->fbtftops.unregister_backlight = fbtft_unregister_backlight;
}
#else
void fbtft_register_backlight(struct device *dev,struct fbtft_par *par) { };
void fbtft_unregister_backlight(struct device *dev,struct fbtft_par *par) { };
#endif
EXPORT_SYMBOL(fbtft_register_backlight);
EXPORT_SYMBOL(fbtft_unregister_backlight);

void fbtft_set_addr_win(struct device *dev,struct fbtft_par *par, int xs, int ys, int xe, int ye)
{
	fbtft_par_dbg(DEBUG_SET_ADDR_WIN, par,
		"%s(xs=%d, ys=%d, xe=%d, ye=%d)\n", __func__, xs, ys, xe, ye);

	/* Column address set */
	write_reg(dev,par, 0x2A,
		(xs >> 8) & 0xFF, xs & 0xFF, (xe >> 8) & 0xFF, xe & 0xFF);

	/* Row adress set */
	write_reg(dev,par, 0x2B,
		(ys >> 8) & 0xFF, ys & 0xFF, (ye >> 8) & 0xFF, ye & 0xFF);

	/* Memory write */
	write_reg(dev,par, 0x2C);
}


void fbtft_reset(struct fbtft_par *par)
{
	if (par->gpio.reset == -1)
		return;
	fbtft_par_dbg(DEBUG_RESET, par, "%s()\n", __func__);
	gpio_set_value(par->gpio.reset, 0);
	udelay(20);
	gpio_set_value(par->gpio.reset, 1);
	mdelay(120);
}


void fbtft_update_display(struct device *dev,struct fbtft_par *par, unsigned start_line, unsigned end_line)
{
	size_t offset, len;
	int ret = 0;
		fbtft_set_addr_win(dev,par, 0, start_line,
				480-1, end_line);
	offset = start_line * 960;
	len = (end_line - start_line + 1) * 960;
	ret = fbtft_write_vmem16_bus8(dev,par, offset, len);
}


void fbtft_update_display2(struct device *dev,struct fbtft_par *par)
{
	size_t offset, len;
	int ret = 0;
	offset = 0;
	len = (319 - 0 + 1) * 960;
	ret = fbtft_write_vmem16_bus8(dev,par, offset, len);
}

void fbtft_mkdirty(struct fb_info *info, int y, int height)
{
	struct fbtft_par *par = info->par;
	struct fb_deferred_io *fbdefio = info->fbdefio;

	/* special case, needed ? */
	if (y == -1) {
		y = 0;
		height = info->var.yres - 1;
	}

	/* Mark display lines/area as dirty */
	spin_lock(&par->dirty_lock);
	if (y < par->dirty_lines_start)
		par->dirty_lines_start = y;
	if (y + height - 1 > par->dirty_lines_end)
		par->dirty_lines_end = y + height - 1;
	spin_unlock(&par->dirty_lock);

	/* Schedule deferred_io to update display (no-op if already on queue)*/
	schedule_delayed_work(&info->deferred_work, fbdefio->delay);
}

/* from pxafb.c */
unsigned int chan_to_field(unsigned chan, struct fb_bitfield *bf)
{
	chan &= 0xffff;
	chan >>= 16 - bf->length;
	return chan << bf->offset;
}

static int init_display(struct device *dev,struct fbtft_par *par)
{
	fbtft_par_dbg(DEBUG_INIT_DISPLAY, par, "%s()\n", __func__);

	fbtft_reset(par);

	/* startup sequence for MI0283QT-9A */
	write_reg(dev,par, ILI9488_SWRESET); /* software reset */
	mdelay(5);
	write_reg(dev,par, ILI9488_DISPOFF); /* display off */

	write_reg(dev,par, ILI9488_CMD_POSITIVE_GAMMA_CTRL, 0x00, 0x03, 0x09, 0x08, 0x16, 0x0A, 0x3F, 0x78, 0x4C, 0x09, 0x0A, 0x08, 0x16, 0x1A, 0x0F);
    write_reg(dev,par, ILI9488_CMD_NEGATIVE_GAMMA_CTRL, 0x00, 0x16, 0x19, 0x03, 0x0F, 0x05, 0x32, 0x45, 0x46, 0x04, 0x0E, 0x0D, 0x35, 0x37, 0x0F);

    write_reg(dev,par, ILI9488_CMD_POWER_CONTROL_1, 0x17, 0x15);
	write_reg(dev,par, ILI9488_CMD_POWER_CONTROL_2, 0x41);

	write_reg(dev,par, ILI9488_CMD_VCOM_CONTROL_1, 0x00, 0x12, 0x80);

	write_reg(dev,par, ILI9488_CMD_MEMORY_ACCESS_CONTROL, 0x48);

	write_reg(dev,par, ILI9488_CMD_INTERFACE_PIXEL_FORMAT, 0x66);
	write_reg(dev,par, ILI9488_CMD_INTERFACE_MODE_CONTROL, 0x80);

	write_reg(dev,par, ILI9488_CMD_FRAME_RATE_CONTROL_NORMAL, 0xA0);

	write_reg(dev,par, ILI9488_CMD_DISPLAY_INVERSION_CONTROL, 0x02);
	write_reg(dev,par, ILI9488_CMD_DISPLAY_FUNCTION_CONTROL, 0x02, 0x02);

	write_reg(dev,par, ILI9488_CMD_SET_IMAGE_FUNCTION, 0x00);

	write_reg(dev,par, ILI9488_CMD_ADJUST_CONTROL_3, 0xA9, 0x51, 0x2C, 0x82);

	write_reg(dev,par, ILI9488_SLPOUT);
	mdelay(120);

	write_reg(dev,par, ILI9488_DISPON);
	mdelay(20);

	return 0;
}

//#define CURVE(num, idx)  curves[num*par->gamma.num_values + idx]
//static int set_gamma(struct fbtft_par *par, unsigned long *curves)
//{
//	int i;
//
//	fbtft_par_dbg(DEBUG_INIT_DISPLAY, par, "%s()\n", __func__);
//
//	for (i = 0; i < par->gamma.num_curves; i++)
//		write_reg(par, 0xE0 + i,
//			CURVE(i, 0), CURVE(i, 1), CURVE(i, 2),
//			CURVE(i, 3), CURVE(i, 4), CURVE(i, 5),
//			CURVE(i, 6), CURVE(i, 7), CURVE(i, 8),
//			CURVE(i, 9), CURVE(i, 10), CURVE(i, 11),
//			CURVE(i, 12), CURVE(i, 13), CURVE(i, 14));
//
//	return 0;
//}
//#undef CURVE


//int fbtft_fb_blank(int blank, struct fb_info *info)
//{
//	struct fbtft_par *par = info->par;
//	int ret = -EINVAL;
//
//	fbtft_dev_dbg(DEBUG_FB_BLANK, par, info->dev, "%s(blank=%d)\n",
//		__func__, blank);
//
//	if (!par->fbtftops.blank)
//		return ret;
//
//	switch (blank) {
//	case FB_BLANK_POWERDOWN:
//	case FB_BLANK_VSYNC_SUSPEND:
//	case FB_BLANK_HSYNC_SUSPEND:
//	case FB_BLANK_NORMAL:
//		ret = par->fbtftops.blank(par, true);
//		break;
//	case FB_BLANK_UNBLANK:
//		ret = par->fbtftops.blank(par, false);
//		break;
//	}
//	return ret;
//}

void fbtft_merge_fbtftops(struct fbtft_ops *dst, struct fbtft_ops *src)
{
	if (src->blank)
		dst->blank = src->blank;
	if (src->register_backlight)
		dst->register_backlight = src->register_backlight;
	if (src->unregister_backlight)
		dst->unregister_backlight = src->unregister_backlight;
//	if (src->set_var)
//		dst->set_var = src->set_var;
}

#define MEM_Y   (7) /* MY row address order */
#define MEM_X   (6) /* MX column address order */
#define MEM_V   (5) /* MV row / column exchange */
#define MEM_L   (4) /* ML vertical refresh order */
#define MEM_H   (2) /* MH horizontal refresh order */
#define MEM_BGR (3) /* RGB-BGR Order */
int set_var(struct device *dev,struct fbtft_par *par)
{
	fbtft_par_dbg(DEBUG_INIT_DISPLAY, par, "%s()\n", __func__);

	fbtft_par_dbg(DEBUG_INIT_DISPLAY, par, "888888888888888  rotate = %d\n", par->info->var.rotate);

	switch (par->info->var.rotate) {
	case 0:
		write_reg(dev,par, 0x36, (1 << MEM_X) | (par->bgr << MEM_BGR));
		break;
	case 270:
		write_reg(dev,par, 0x36,
			(1<<MEM_V) | (1 << MEM_L) | (par->bgr << MEM_BGR));
		break;
	case 180:
		write_reg(dev,par, 0x36, (1 << MEM_Y) | (par->bgr << MEM_BGR));
		break;
	case 90:
		write_reg(dev,par, 0x36, (1 << MEM_Y) | (1 << MEM_X) |
				     (1 << MEM_V) | (par->bgr << MEM_BGR));
		break;
	}

	return 0;
}


/**
 * fbtft_framebuffer_alloc - creates a new frame buffer info structure
 *
 * @display: pointer to structure describing the display
 * @dev: pointer to the device for this fb, this can be NULL
 *
 * Creates a new frame buffer info structure.
 *
 * Also creates and populates the following structures:
 *   info->fbops
 *   info->fbdefio
 *   info->pseudo_palette
 *   par->fbtftops
 *   par->txbuf
 *
 * Returns the new structure, or NULL if an error occurred.
 *
 */
struct fb_info *fbtft_framebuffer_alloc(struct fbtft_display *display,
					struct device *dev)
{
	struct fb_info *info;
	struct fbtft_par *par;
	struct fb_ops *fbops = NULL;
	struct fb_deferred_io *fbdefio = NULL;
	struct fbtft_platform_data *pdata = dev->platform_data;
	u8 *vmem = NULL;
	void *txbuf = NULL;
	void *buf = NULL;
	unsigned width;
	unsigned height;
	int txbuflen = display->txbuflen;
	unsigned bpp = display->bpp;
	unsigned fps = display->fps;
	int vmem_size, i;
	int *init_sequence = display->init_sequence;
	char *gamma = display->gamma;
	unsigned long *gamma_curves = NULL;

	/* sanity check */
	if (display->gamma_num * display->gamma_len > FBTFT_GAMMA_MAX_VALUES_TOTAL) {
		dev_err(dev,
			"%s: FBTFT_GAMMA_MAX_VALUES_TOTAL=%d is exceeded\n",
			__func__, FBTFT_GAMMA_MAX_VALUES_TOTAL);
		return NULL;
	}

	/* defaults */
	if (!fps)
		fps = 20;
	if (!bpp)
		bpp = 16;

	if (!pdata) {
		dev_err(dev, "platform data is missing\n");
		return NULL;
	}

	/* override driver values? */
	if (pdata->fps)
		fps = pdata->fps;
	if (pdata->txbuflen)
		txbuflen = pdata->txbuflen;
	if (pdata->display.init_sequence)
		init_sequence = pdata->display.init_sequence;
	if (pdata->gamma)
		gamma = pdata->gamma;
	if (pdata->display.debug)
		display->debug = pdata->display.debug;
	if (pdata->display.backlight)
		display->backlight = pdata->display.backlight;
	if (pdata->display.width)
		display->width = pdata->display.width;
	if (pdata->display.height)
		display->height = pdata->display.height;
	if (pdata->display.buswidth)
		display->buswidth = pdata->display.buswidth;
	if (pdata->display.regwidth)
		display->regwidth = pdata->display.regwidth;

	display->debug |= debug;
	fbtft_expand_debug_value(&display->debug);

	switch (pdata->rotate) {
	case 90:
	case 270:
		width =  display->height;
		height = display->width;
		break;
	default:
		width =  display->width;
		height = display->height;
	}

	vmem_size = display->width * display->height * bpp / 8;
	vmem = vzalloc(vmem_size);
	if (!vmem)
		goto alloc_fail;

	fbops = devm_kzalloc(dev, sizeof(struct fb_ops), GFP_KERNEL);
	if (!fbops)
		goto alloc_fail;

	fbdefio = devm_kzalloc(dev, sizeof(struct fb_deferred_io), GFP_KERNEL);
	if (!fbdefio)
		goto alloc_fail;

	buf = devm_kzalloc(dev, 128, GFP_KERNEL);
	if (!buf)
		goto alloc_fail;

	if (display->gamma_num && display->gamma_len) {
		gamma_curves = devm_kzalloc(dev, display->gamma_num * display->gamma_len * sizeof(gamma_curves[0]),
						GFP_KERNEL);
		if (!gamma_curves)
			goto alloc_fail;
	}

	info = framebuffer_alloc(sizeof(struct fbtft_par), dev);
	if (!info)
		goto alloc_fail;

	info->screen_base = (u8 __force __iomem *)vmem;
	info->fbops = fbops;
	info->fbdefio = fbdefio;

	fbops->owner        =      dev->driver->owner;

	fbdefio->delay =           HZ/fps;
//	fbdefio->deferred_io =     fbtft_deferred_io;
	fb_deferred_io_init(info);

	strncpy(info->fix.id, dev->driver->name, 16);
//	info->fix.type =           FB_TYPE_PACKED_PIXELS;
//	info->fix.visual =         FB_VISUAL_TRUECOLOR;
//	info->fix.xpanstep =	   0;
//	info->fix.ypanstep =	   0;
//	info->fix.ywrapstep =	   0;
//	info->fix.line_length =    width*bpp/8;
//	info->fix.accel =          FB_ACCEL_NONE;
//	info->fix.smem_len =       vmem_size;

	info->var.rotate =         pdata->rotate;
//	info->var.xres =           width;
//	info->var.yres =           height;
//	info->var.xres_virtual =   info->var.xres;
//	info->var.yres_virtual =   info->var.yres;
//	info->var.bits_per_pixel = bpp;
//	info->var.nonstd =         1;

	/* RGB565 */
//	info->var.red.offset =     11;
//	info->var.red.length =     5;
//	info->var.green.offset =   5;
//	info->var.green.length =   6;
//	info->var.blue.offset =    0;
//	info->var.blue.length =    5;
//	info->var.transp.offset =  0;
//	info->var.transp.length =  0;

//	info->flags =              FBINFO_FLAG_DEFAULT | FBINFO_VIRTFB;

	par = info->par;
	par->info = info;
	par->pdata = dev->platform_data;
	par->debug = display->debug;
	par->buf = buf;
	spin_lock_init(&par->dirty_lock);
	par->bgr = pdata->bgr;
	par->startbyte = pdata->startbyte;
	par->init_sequence = init_sequence;
	par->gamma.curves = gamma_curves;
	par->gamma.num_curves = display->gamma_num;
	par->gamma.num_values = display->gamma_len;
	mutex_init(&par->gamma.lock);
	info->pseudo_palette = par->pseudo_palette;

	if (par->gamma.curves && gamma) {
		if (fbtft_gamma_parse_str(dev,par,
			par->gamma.curves, gamma, strlen(gamma)))
			goto alloc_fail;
	}

	/* Transmit buffer */
	if (txbuflen == -1)
		txbuflen = vmem_size + 2; /* add in case startbyte is used */

#ifdef __LITTLE_ENDIAN
	if ((!txbuflen) && (bpp > 8))
		txbuflen = PAGE_SIZE; /* need buffer for byteswapping */
#endif

	if (txbuflen > 0) {
		if (dma) {
			dev->coherent_dma_mask = ~0;
			txbuf = dmam_alloc_coherent(dev, txbuflen, &par->txbuf.dma, GFP_DMA);
		} else {
			txbuf = devm_kzalloc(par->info->device, txbuflen, GFP_KERNEL);
		}
		if (!txbuf)
			goto alloc_fail;
		par->txbuf.buf = txbuf;
		par->txbuf.len = txbuflen;
	}

	/* Initialize gpios to disabled */
	par->gpio.reset = -1;
	par->gpio.dc = -1;
//	par->gpio.rd = -1;
//	par->gpio.wr = -1;
//	par->gpio.cs = -1;
//	par->gpio.latch = -1;
	for (i = 0; i < 16; i++) {
		par->gpio.db[i] = -1;
		par->gpio.led[i] = -1;
		par->gpio.aux[i] = -1;
	}

	if (display->backlight)
		par->fbtftops.register_backlight = fbtft_register_backlight;

	/* use driver provided functions */
	fbtft_merge_fbtftops(&par->fbtftops, &display->fbtftops);

	return info;

alloc_fail:
	vfree(vmem);

	return NULL;
}
EXPORT_SYMBOL(fbtft_framebuffer_alloc);

///**
// * fbtft_framebuffer_release - frees up all memory used by the framebuffer
// *
// * @info: frame buffer info structure
// *
// */
//void fbtft_framebuffer_release(struct fb_info *info)
//{
//	fb_deferred_io_cleanup(info);
//	vfree(info->screen_base);
//	framebuffer_release(info);
//}
//EXPORT_SYMBOL(fbtft_framebuffer_release);


/**
 * fbtft_verify_gpios() - Generic verify_gpios() function
 * @par: Driver data
 *
 * Uses @spi, @pdev and @buswidth to determine which GPIOs is needed
 *
 * Return: 0 if successful, negative if error
 */
int fbtft_verify_gpios(struct device *dev,struct fbtft_par *par)
{
	struct fbtft_platform_data *pdata;
	int i;

	fbtft_par_dbg(DEBUG_VERIFY_GPIOS, par, "%s()\n", __func__);

	pdata = dev->platform_data;
	if (pdata->display.buswidth != 9 && par->startbyte == 0 && \
							par->gpio.dc < 0) {
		dev_err(dev,
			"Missing info about 'dc' gpio. Aborting.\n");
		return -EINVAL;
	}

	if (!par->pdev)
		return 0;

//	if (par->gpio.wr < 0) {
//		dev_err(par->info->device, "Missing 'wr' gpio. Aborting.\n");
//		return -EINVAL;
//	}
	for (i = 0; i < pdata->display.buswidth; i++) {
		if (par->gpio.db[i] < 0) {
			dev_err(dev,
				"Missing 'db%02d' gpio. Aborting.\n", i);
			return -EINVAL;
		}
	}

	return 0;
}

/* returns 0 if the property is not present */
static u32 fbtft_of_value(struct device_node *node, const char *propname)
{
	int ret;
	u32 val = 0;

	ret = of_property_read_u32(node, propname, &val);
	if (ret == 0)
		pr_info("%s: %s = %u\n", __func__, propname, val);

	return val;
}

static struct fbtft_platform_data *fbtft_probe_dt(struct device *dev)
{
	struct device_node *node = dev->of_node;
	struct fbtft_platform_data *pdata;

	if (!node) {
		dev_err(dev, "Missing platform data or DT\n");
		return ERR_PTR(-EINVAL);
	}

	pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);
	if (!pdata)
		return ERR_PTR(-ENOMEM);

	pdata->display.width = fbtft_of_value(node, "width");
	pdata->display.height = fbtft_of_value(node, "height");
	pdata->display.regwidth = fbtft_of_value(node, "regwidth");
	pdata->display.buswidth = fbtft_of_value(node, "buswidth");
	pdata->display.backlight = fbtft_of_value(node, "backlight");
	pdata->display.bpp = fbtft_of_value(node, "bpp");
	pdata->display.debug = fbtft_of_value(node, "debug");
	pdata->rotate = fbtft_of_value(node, "rotate");
	pdata->bgr = of_property_read_bool(node, "bgr");
	pdata->fps = fbtft_of_value(node, "fps");
	pdata->txbuflen = fbtft_of_value(node, "txbuflen");
	pdata->startbyte = fbtft_of_value(node, "startbyte");
	of_property_read_string(node, "gamma", (const char **)&pdata->gamma);

	if (of_find_property(node, "led-gpios", NULL))
		pdata->display.backlight = 1;
//	if (of_find_property(node, "init", NULL))
//		pdata->display.fbtftops.init_display = fbtft_init_display_dt;
//	pdata->display.fbtftops.request_gpios = fbtft_request_gpios_dt;

	return pdata;
}

/**
 * fbtft_probe_common() - Generic device probe() helper function
 * @display: Display properties
 * @sdev: SPI device
 * @pdev: Platform device
 *
 * Allocates, initializes and registers a framebuffer
 *
 * Either @sdev or @pdev should be NULL
 *
 * Return: 0 if successful, negative if error
 */
int fbtft_probe_common(struct fbtft_display *display,
			struct spi_device *sdev, struct platform_device *pdev)
{
	struct device *dev;
	struct fb_info *info;
	struct fbtft_par *par;
	struct fbtft_platform_data *pdata;
	int ret;

	if (sdev)
		dev = &sdev->dev;
	else
		dev = &pdev->dev;

//	if (unlikely(display->debug & DEBUG_DRIVER_INIT_FUNCTIONS))
//		dev_info(dev, "%s()\n", __func__);

	pdata = dev->platform_data;
	if (!pdata) {
		pdata = fbtft_probe_dt(dev);
		if (IS_ERR(pdata))
			return PTR_ERR(pdata);
		dev->platform_data = pdata;
	}

	info = fbtft_framebuffer_alloc(display, dev);
	if (!info)
		return -ENOMEM;

	par = info->par;
	par->spi = sdev;
	par->pdev = pdev;

	if (display->buswidth == 0) {
		dev_err(dev, "buswidth is not set\n");
		return -EINVAL;
	}

	ret = fbtft_request_gpios_dt(dev,par);
		ret = fbtft_verify_gpios(dev,par);

	ret = init_display(dev,par);

	ret = set_var(dev,par);

	/* update the entire display */

	fbtft_set_addr_win(dev,par, 0, 0,
				479, 319);

	fbtft_update_display2(dev,par);

//	ret = set_gamma(par, par->gamma.curves);
//	if (ret < 0)
//		goto out_release;

	return 0;

//out_release:
//	fbtft_framebuffer_release(info);

//	return ret;
}
EXPORT_SYMBOL(fbtft_probe_common);

/**
 * fbtft_remove_common() - Generic device remove() helper function
 * @dev: Device
 * @info: Framebuffer
 *
 * Unregisters and releases the framebuffer
 *
 * Return: 0 if successful, negative if error
 */
int fbtft_remove_common(struct device *dev, struct fb_info *info)
{
	struct fbtft_par *par;

	if (!info)
		return -EINVAL;
	par = info->par;
	if (par)
		fbtft_par_dbg(DEBUG_DRIVER_INIT_FUNCTIONS, par,
			"%s()\n", __func__);
//	fbtft_framebuffer_release(info);

	return 0;
}
EXPORT_SYMBOL(fbtft_remove_common);

MODULE_LICENSE("GPL");
